package net.cl.tools;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

public class CaptchaBuilder {
	
	private static final String DEFAULT_FORMAT = "jpeg";

	private static BufferedImage build1(String str, BufferedImage image) {
		Graphics2D g = (Graphics2D) image.getGraphics();
		Font font = new Font("Times New Roman", Font.PLAIN, 55);
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, image.getWidth(), image.getHeight());
		g.setFont(font);
		g.setPaint(Color.RED);
		g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
		FontRenderContext context = g.getFontRenderContext();
		Rectangle2D bounds = font.getStringBounds(str, context);
		double x = (image.getWidth() - bounds.getWidth()) / 2;
		double y = (image.getHeight() - bounds.getHeight()) / 2;
		double ascent = -bounds.getY();
		double baseY = y + ascent;
		g.drawString(str, (int) x, (int) baseY);
		g.dispose();
		return image;
	}

	public static void build(String str, int width, int height, File file) {
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		try {
			ImageIO.write(build1(str, image), DEFAULT_FORMAT, file);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void build(String str, int width, int height, OutputStream os) {
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		try {
			ImageIO.write(build1(str, image), DEFAULT_FORMAT, os);
			os.flush();
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void build(String str, int width, int height, HttpServletResponse response) {
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		OutputStream os = null;
		try {
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.setContentType("image/jpg");
			os = response.getOutputStream();
			ImageIO.write(build1(str, image), DEFAULT_FORMAT, os);
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
